import pymysql
from gmssl.sm4 import CryptSM4, SM4_ENCRYPT, SM4_DECRYPT
import socket

def file_manage(file_name):             #处理文本文件
    file_content = ''
    try:
        with open(file_name, encoding='utf-8') as file_obj:
            # 定义一个变量，来保存文件的内容
            #file_content = ''
            # 定义一个变量，来指定每次读取的大小
            chunk = 100
            # 创建一个循环来读取文件内容
            while True:
                # 读取chunk大小的内容
                content = file_obj.read(chunk)

                # 检查是否读取到了内容
                if not content:
                    # 内容读取完毕，退出循环
                    break

                # 输出内容
                # print(content,end='')
                file_content += content
    except FileNotFoundError:
        print('{}  no file!'.format(file_name))
    return file_content

def file_enc(content):    #文件加密上传
    key = b'3l5butlj26hvv313'
    crypt_sm4 = CryptSM4()
    crypt_sm4.set_key(key, SM4_ENCRYPT)
    encrypt_value = crypt_sm4.crypt_ecb(content.encode())  # bytes类型
    #encrypt_value = encrypt_value.decode('utf-8')   #转回str
    return encrypt_value.hex()

def file_dec(encrypt_value):    #文件解密
    key = b'3l5butlj26hvv313'
    crypt_sm4 = CryptSM4()
    crypt_sm4.set_key(key, SM4_DECRYPT)
    decrypt_value = crypt_sm4.crypt_ecb(bytes.fromhex(encrypt_value))  # bytes类型
    print(decrypt_value.decode())
    return decrypt_value.decode()


'''def connect_Ic(Ic):    #上传token
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.connect (('47.92.99.28',2000))
    print(s.recv(1024).decode('utf-8'))
    Ic = str(Ic)
    s.send(Ic.encode())

    for i in range(0,len(token)):
        for j in range(0,len(token[0])):
            s.send(str(token[i][j]).encode())
            print(s.recv(1024).decode('utf-8'))
    s.send(b'12345')          #终止符号
    '''

def connect_search(column,column_msk,T,Ic,Ir,I,s1):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('47.92.99.28', 2000))
    print(s.recv(1024).decode('utf-8'))


    column = str(column)
    s.send(column.encode())
    s.send(b'**')
    #print(column)
    #print("column----------")

    column_msk = str(column_msk)
    s.send(column_msk.encode())
    s.send(b'**')
    #print(column_msk)
    #print("column_msk----------")

    T = str(T)
    s.send(T.encode())
    s.send(b'**')
    #print(T)
    #print("T----------")

    Ir = str(Ir)
    s.send(Ir.encode())
    s.send(b'**')
    #print(Ir)
    #print("Ir----------")

    Ic = str(Ic)
    s.send(Ic.encode())
    s.send(b'**')
    #print(Ic)
    #print("Ic----------")

    I = str(I)
    s.send(I.encode())
    s.send(b'**')
    #print(I)
    #print("I----------")

    s1=str(s1)
    s.send(s1.encode())
    #s.send(b'**')
    #print(s1)

    s.close()
def get_enfile():
    enfile=''
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('47.92.99.28', 5000))
    while True:
        data = s.recv(1024)
        enfile = enfile + data.decode('utf-8')
        if not data or data.decode() =='*' :
            break
    s.close()
    return  enfile

'''res_file=''
    data = s.recv(1024)
    res_file = res_file + data.decode('utf-8')
    print(res_file)
'''


def f_upload(filename):
    db = pymysql.connect(
        host='47.92.99.28',
        port=3306,
        user='root',
        password='123456',
        database='file',
        charset='utf8'
    )  # 连接数据库
    file_name=filename
    f_content = ''
    f_content = file_manage(file_name)
    f_enc = file_enc(f_content)
    file_dec(f_enc)
    cursor = db.cursor()  # 游标
    sql_upload = "insert into file_upload(filename,fcontent) value ('{}', '{}')".format(file_name,f_enc)

    cursor.execute(sql_upload)  # 执行SQL语句
    cursor.close()
    db.commit()  # 提交数据
    db.close()

def f_select(id):
    db = pymysql.connect(
        host='47.92.99.28',
        port=3306,
        user='root',
        password='123456',
        database='file',
        charset='utf8'
    )  # 连接数据库
    f_id = id
    sql_select = "select fcontent from file_upload where id='{}'".format(f_id)
    cursor = db.cursor()
    cursor.execute(sql_select)
    res=cursor.fetchone()
    print(res)
    cursor.close()
    db.commit()
    db.close()
if __name__ == '__main__':
    '''
token=[[23,23,12,65],[21,34,67],[21,54,46]]
connect(token)
    

db = pymysql.connect(
        host='47.92.99.28',
        port=3306,
        user='root',
        password='123456',
        database='file',
        charset='utf8'
    )  # 连接数据库

    file_name = 'C:/Users/CRAZYBULU/Desktop/data.txt'
    f_content = file_manage(file_name)
    f_enc = file_enc(f_content)
    file_dec(f_enc)
    cursor = db.cursor()  # 游标
    sql = f"insert into file_upload(filename,fcontent) value ('{file_name}', '{f_enc}')"

    cursor.execute(sql)  # 执行SQL语句
    cursor.close()
    db.commit()  # 提交数据
    db.close()
    '''






